<template>
 <div class="city-container">
  <div>
   <van-nav-bar
    title="城市列表"
    left-text="返回"
    left-arrow
    @click-left="$router.back()"
   />
  </div>
  <!-- 当前城市 -->
  <van-index-bar :index-list="indexList">
   <van-index-anchor index="1">当前城市</van-index-anchor>
    <van-cell :title="city"/>
   <!-- 热门城市 -->
   <van-index-anchor index="热">热门城市</van-index-anchor>
   <van-cell
    :title="item.label"
    v-for="(item, index) in HotCity"
    :key="index"
    @click="CityFn(item.label,item.value)"
   />
   <!-- 城市 -->
   <div v-for="(item, index) in CiTyList" :key="index">
    <!-- toUpperCase 将单词进行大写处理 -->
    <van-index-anchor :index="index.toUpperCase()">{{
     index.toUpperCase()
    }}</van-index-anchor>
    <van-cell
     :title="city.label"
     v-for="(city, index) in item"
     :key="index"
     @click="CityFn()"
    />
   </div>
  </van-index-bar>
  <div class="loading" v-if="Show">
   <van-loading size="40px" color="#333333">加载中...</van-loading>
  </div>
 </div>
</template>

<script>
import { City, HostCity } from '@/api/article'
export default {
  data () {
    return {
      Show: true,
      now: {},
      HotCity: [],
      CiTyList: {},
      indexList: [],
      city: localStorage.getItem('city') || ''
    }
  },
  methods: {
    CityFn (item) {
      if (item) {
        localStorage.setItem('city', item)
        this.$router.back()
      } else {
        this.$toast.success('该城市没有房源')
      }
    }
  },
  async created () {
    const res = await City(1)
    this.Show = false

    const cityInAbc = {}
    res.body.forEach((item) => {
      if (cityInAbc[item.short[0]]) {
        cityInAbc[[item.short[0]]].push(item)
      } else {
        cityInAbc[item.short[0]] = [item]
      }
    })

    // 拿出所有键并排序 作为索引栏
    const list = Object.keys(cityInAbc).sort()
    for (let i = 0; i < list.length; i++) {
      this.CiTyList[list[i]] = cityInAbc[list[i]]
    }
    list.forEach((item, index) => {
      list[index] = item.toUpperCase()
    })
    this.indexList = list
    this.indexList.unshift('热')
    this.indexList.unshift('#')

    const res2 = await HostCity()
    // console.log(res2)
    this.HotCity = res2.body
  }
}
</script>

<style lang="less" scoped>
.city-container {
 min-height: 667px;
 .top-header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 100;
 }
}

::v-deep .van-index-anchor {
 padding: 6px 10px;
 font-size: 14px;
 color: #999999;
}
::v-deep .van-cell,
.van-cell__title {
 font-size: 18px;
}
::v-deep .van-cell {
 height: 50px;
}
::v-deep .van-index-bar__sidebar {
 top: 50%;
}
::v-deep .van-index-bar__index {
 width: 17px;
 height: 17px;
 font-size: 14px;
 color: #333333;
 border-radius: 50%;
 margin-bottom: 10px;
 margin-right: 5px;
 text-align: center;
 line-height: 20px;
 padding: 0;
}
::v-deep .van-index-bar__index--active {
 background-color: #00c178;
}
.loading {
 position: absolute;
 top: 50%;
 left: 50%;
 transform: translateX(-50px);
}
</style>
